<template>
  <div class="number">
    <div class="num">
      购买数量:
      <div class="num-z">
        <button type="button" class="num-f" @click="reduce()">-</button>
        <input type="number" @input="userinput(stock_quantity)" ref="numbox" v-model="num" />
        <button type="button" class="num-z" @click="plus(stock_quantity)">+</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "number",
  data() {
    return {
      num: 1
    };
  },
  methods: {
    plus(num) {
      if (this.num >= num) {
        this.num = num;
      } else {
        this.num = parseInt(this.num) + 1;
      }
    },
    userinput(num) {
      if (this.num <= 1) {
        this.num = 1;
      } else if (this.num >= num) {
        this.num = num;
      }
    },
    countChange() {
      console.log(this.$refs.numbox.value);
    },
    reduce() {
      if (this.num <= 1) {
        this.num = 1;
      } else {
        this.num = parseInt(this.num) - 1;
      }
    }
  },
  props: ["stock_quantity"],
  watch: {
    num(newVal) {
        this.$emit('getCount', parseInt(newVal))
    },
    stock_quantity(newVal) {
        // stock_quantity的值是异步加载的，需要监听加载之后的值，把值传给参数,现在不是异步加载，所以目前没有用
        console.log(newVal+1)
    }
  }
};
</script>

<style lang="scss" scoped>
.number {
  .num {
    margin-bottom: 10px;
    .num-z {
      display: inline-block;
      border: 1px solid #bbb;
      border-radius: 6px;
      button {
        width: 40px;
        height: 40px;
        background: #f9f9f9;
        border: none;
        outline: none;
        border-radius: 6px;
        margin: 0;
        &:active {
          background: #bbb;
        }
      }
      input {
        outline: none;
        width: 38px;
        height: 38px;
        border: #bbb;
        text-align: center;
      }
    }
  }
}
</style>